//
//  AlipayViewController.m
//  iStore
//
//  Created by MacDev on 15/5/7.
//  Copyright (c) 2015年 mirrtalk. All rights reserved.
//

#import "Alipay.h"
#import "RequestEngine.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "DataSigner.h"
#import "MBProgressHUD.h"

@interface Alipay ()

@end

@implementation Alipay


- (void)alipay:(NSDictionary *)dict
{
    // *商户的唯一的parnter和seller。
    // *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
    
    NSString *partner = @"2088801707880812";
    NSString *seller = @"mirrtalk@foxmail.com";
    NSString *privateKey = @"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ9zFrMUxLmCWxM6C25IFkx5VtR5BrqB2X9bbksfgsgO4xog41Zx1hCM5f4nbvAg4kZxvkCd3YRHEQXhC/3cSV6Qoii+QY7gzmAPo+9H5nD8irOxyRVAnEEhLhxJlSJPdPLlN2P/mayJG6alZyLRkslvVTawef0JBLDEswtS+HIBAgMBAAECgYAhxGa/QBu1SaTt+nHnRf7q7Rt1XbgOEWe1L/C4mhDBO13e764VZYA2+w/N9h3pXp1s27O1zXjXBZHWU+WNOnSS66foaj0dbTM4aUXaund2Wsd4Dr9CB14cQOtul3tqwk6IoJpRVnv6cnMzvkurbM7vdIHHKCycPfWC65ZD5ClEjQJBAM6ozydN45xRV5ucT6fTMWG8G4V+k3G1xm0NpLMrTD/YJFEf+FB3TSXqFLgPF5vPrLNKCfCY1dT2DxPyJAeCHRMCQQDFhMaBZeyhmx/LsdEW1wKL/7LJDOeKPrWZLy1KyciHAKIa0NUL3t1cHf8FWhPxth88JAuH3a2Co1Huj0uzxDsbAkEAup0dUvS20HVzkwU3uOiw8vyWLZn7MvdeUyO60kAK/qwDP26LIL5aYB5cz0hxnTWPUedNyoF4tnHrc6t4dX89GQJBAJdqccJAoGZCxN0iM2eO7CTmn+gAPH9+EzibMd1jUpYrphlofenbr1YuqJExvJhPRSKVf0Fobtr22JhIwX/NroECQHeiKuZdD+gZ1wdk0SZU3Qazv+DZw2vAs3m5eHHLNZrkH3ID2yhubivpMY3Mkcd8ogAzAp5bKRLaXmijueDeuzc=";
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = dict[@"orderFormNumber"];//订单ID
    order.productName = @"商品标签";//商品标签
    order.productDescription = @"商品描述";//商品描述
    order.amount = [NSString stringWithFormat:@"%@",dict[@"totalFee"]];//商品金额
    order.notifyURL = dict[@"notifyURL"];//回调URL
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    //    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"alisdkdemo";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        //       NSLog(@"orderSpec = %@",orderString);
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            //       NSLog(@"reslut = %@",resultDic);
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"])  {
                NSString *userID = [[NSUserDefaults standardUserDefaults]objectForKey:kUserId];
                NSDictionary *redic = @{@"orderFormNumber":order.tradeNO,@"userID":userID};
                [RequestEngine userAppNotifyWithDic:redic completed:^(NSString *errorcode, NSDictionary *resultdict) {
                    //  NSLog(@"notify=%@",errorcode);
                    if ([errorcode isEqualToString:@"0"]) {
                        [[NSNotificationCenter defaultCenter]postNotificationName:kpaySuccess object:self userInfo:@{@"success":@"0"}];
                        
                    }
                    else {
                        [[NSNotificationCenter defaultCenter]postNotificationName:kpaySuccess object:self userInfo:@{@"success":@"1"}];
                    }
                    
                }];
                
            }
            
            else if ([resultDic[@"resultStatus"] isEqualToString:@"6002"])  {
                alert(@"网络错误")
            }
        }];
    }
    
}


@end
